package com.hbnu.controller;

import com.hbnu.pojo.User;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.text.SimpleDateFormat;

@Controller
//@RestController // Controller 注解和ResponseBody 注解的合集
public class HomeController {
    @RequestMapping("/home")  // RequestMapping 注解用于映射请求
    public String homePage(){
        return "home"; // 返回 home.jsp
    }
//    @RequestMapping("/param1")
    @GetMapping("/param1")  // GetMapping 注解用于映射请求， 处理get请求
    @ResponseBody // 返回字符串，不会跳转到其他页面
    public String param1(@RequestParam("username") String username, Integer age){
        System.out.println("username = " + username + ",age = " + age);
        return "username = " + username + ",age = " + age;
    }

    @GetMapping("/param2")
    @ResponseBody
    public String param2(User user){
        System.out.println("user = " + user);
        return "user = " + user;
    }

    // 自定义接受收日期格式的数据
    @InitBinder
    public void InitBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
    }
    @GetMapping("/param3")
    @ResponseBody
    public String param3(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println("date = " + sdf.format(date));
        return "date = " + sdf.format(date);
    }

    @GetMapping(value = "/encoding",produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String encoding(String username, String address){
        System.out.println("接收到的用户名：" + username + ",接收到的地址：" + address);
        return "接收到的用户名： " + username + ",接收到的地址：" + address;
    }

    @GetMapping("/forward")
    public String forward(){
        System.out.println("收到请求，但转发给其他方法处理......");
        return "forward:/home";
    }
    @GetMapping("/redirect")
    public String redirect(){
        System.out.println("收到请求，但重定向给其他方法处理......");
        return "redirect:/home";
    }
    @GetMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("username","张三");
        model.addAttribute("address","北京");
        return "home";
    }
    @GetMapping("/getUser")
    @ResponseBody
    public User getUser(){
        User user = new User();
        user.setUsername("张三");
        user.setPassword("123456");
        user.setEmail("123@qq.com");
        user.setPhone("12345678901");
        user.setBalance(1000.0);
        return user;
    }
}
